"""
Python-Java通信协议定义
标准化数据格式和通信规范
"""

from dataclasses import dataclass
from typing import Dict, Any, Optional, List
from enum import Enum

class ActionType(Enum):
    """支持的操作类型"""
    PREPROCESS = "preprocess"
    GENERATE_BASE = "generate_base"
    VALIDATE = "validate"
    ENHANCE_ANIMATIONS = "enhance_animations"

class ResponseStatus(Enum):
    """响应状态"""
    SUCCESS = "success"
    ERROR = "error"
    WARNING = "warning"

@dataclass
class IntegrationRequest:
    """Java->Python请求数据结构"""
    action: str
    input_path: str
    options: Dict[str, Any]
    request_id: str
    
    def validate(self) -> bool:
        """验证请求格式"""
        if not self.action or self.action not in [e.value for e in ActionType]:
            return False
        if not self.input_path:
            return False
        if not self.request_id:
            return False
        return True

@dataclass
class IntegrationResponse:
    """Python->Java响应数据结构"""
    success: bool
    message: str
    data: Dict[str, Any]
    request_id: str = ""
    processing_time: float = 0.0
    warnings: List[str] = None
    
    def __post_init__(self):
        if self.warnings is None:
            self.warnings = []

class IntegrationProtocol:
    """集成协议处理器"""
    
    # 支持的选项键值
    SUPPORTED_OPTIONS = {
        'theme': str,
        'output_format': str,
        'enable_animations': bool,
        'animation_engine': str,
        'quality': str,
        'timeout_seconds': int,
        'verbose': bool,
        'slide_dimensions': dict,
        'font_settings': dict
    }
    
    # 默认选项值
    DEFAULT_OPTIONS = {
        'theme': 'default',
        'output_format': 'json',
        'enable_animations': True,
        'animation_engine': 'aspose',
        'quality': 'normal',
        'timeout_seconds': 300,
        'verbose': False
    }
    
    @staticmethod
    def validate_options(options: Dict[str, Any]) -> List[str]:
        """验证选项格式"""
        errors = []
        
        for key, value in options.items():
            if key in IntegrationProtocol.SUPPORTED_OPTIONS:
                expected_type = IntegrationProtocol.SUPPORTED_OPTIONS[key]
                if not isinstance(value, expected_type):
                    errors.append(f"选项 '{key}' 应为 {expected_type.__name__} 类型，实际为 {type(value).__name__}")
            else:
                errors.append(f"不支持的选项: '{key}'")
        
        return errors
    
    @staticmethod
    def merge_with_defaults(options: Dict[str, Any]) -> Dict[str, Any]:
        """合并默认选项"""
        merged = IntegrationProtocol.DEFAULT_OPTIONS.copy()
        merged.update(options)
        return merged
    
    @staticmethod
    def create_success_response(data: Dict[str, Any], message: str = "操作成功", 
                              request_id: str = "", processing_time: float = 0.0) -> IntegrationResponse:
        """创建成功响应"""
        return IntegrationResponse(
            success=True,
            message=message,
            data=data,
            request_id=request_id,
            processing_time=processing_time
        )
    
    @staticmethod
    def create_error_response(error_message: str, request_id: str = "", 
                            details: Dict[str, Any] = None) -> IntegrationResponse:
        """创建错误响应"""
        return IntegrationResponse(
            success=False,
            message=error_message,
            data=details or {},
            request_id=request_id
        )

# 动画配置数据结构
@dataclass
class AnimationConfig:
    """动画配置"""
    target_element: str
    effect_type: str
    timing: Dict[str, float]
    properties: Dict[str, Any] = None
    
    def __post_init__(self):
        if self.properties is None:
            self.properties = {}

@dataclass
class SlideConfig:
    """幻灯片配置"""
    index: int
    title: str
    content: List[Dict[str, Any]]
    animations: List[AnimationConfig] = None
    layout: Dict[str, Any] = None
    
    def __post_init__(self):
        if self.animations is None:
            self.animations = []
        if self.layout is None:
            self.layout = {}

@dataclass
class PresentationConfig:
    """演示文稿配置"""
    metadata: Dict[str, str]
    settings: Dict[str, Any]
    slides: List[SlideConfig]
    
    def to_java_format(self) -> Dict[str, Any]:
        """转换为Java端期望的JSON格式"""
        return {
            "metadata": self.metadata,
            "settings": self.settings,
            "slides": [
                {
                    "index": slide.index,
                    "title": slide.title,
                    "content": slide.content,
                    "animations": [
                        {
                            "target_element": anim.target_element,
                            "effect_type": anim.effect_type,
                            "timing": anim.timing,
                            "properties": anim.properties
                        }
                        for anim in slide.animations
                    ],
                    "layout": slide.layout
                }
                for slide in self.slides
            ]
        }